<template>
  <div>

    <!-- <PackBack></PackBack> -->
    <div>
      <!-- 搜索框 -->
      <van-search v-model="value" show-action placeholder="请输入搜索关键词">
        <template #action>
          <van-button
            size="small"
            type="primary"
            style="min-width: 70px"
            @click="() => methods.onSearch(value)"
            >搜索</van-button
          >
        </template>
      </van-search>
      <!-- 搜索框 -->

      <!-- 搜索历史 -->
      <div v-if="!isSearch">
        <div class="weight pls">历史搜索</div>
        <div class="historys">
          <!-- <div>肉</div>
          <div>大帅</div>
          <div>大帅逼</div>
          <div>包浆</div>
          <div>蒋</div>
          <div>蛋</div> -->
          <div v-for="(item,i) in myhistory" :key="i" @click="methods.historySearch(item)">
            {{item}}
          </div>
        </div>

        <div style="text-align: center; font-size: 12px" class="hui mts">
          清空搜索记录
        </div>
      </div>
      <!-- 搜索历史 -->

      <div v-if="isSearch">
        <van-skeleton title :row="10" :loading="isFirst">



          <van-pull-refresh v-model="loadingx" @refresh="methods.onRefresh()">








        <div class="shoplist" style="margin-bottom: 100px;">
          <div v-if="shopData.length!=0">
          <div class="shop" v-for="item in shopData" :key="item.id">
            <div style="display: flex; width: 100%" class="shop-left pts pbs">
              <div class="imgs pls" @click="methods.goDetail(item.id)">
                <img
                  :src="item.photo"
                  class="shop-img"
                  width="90"
                  height="90"
                  style="border-radius: 5px"
                  alt=""
                />
              </div>

              <div class="shop-right prs" style="flex: 1; margin-left: 10px">
                <div>
                  <!-- 0 -->
                  <p class="weight" style="font-size: 14px">{{ item.name }}</p>
                  <!-- 1 -->
                  <div class="myflex" style="width: 100%">
                    <div>
                      <p class="font_x hui">{{ item.specs }}</p>
                    </div>
                    <div>
                      <van-tag type="primary">{{ item.supplier }}</van-tag>
                    </div>
                  </div>
                  <!-- 2 -->
                  <div class="myflex" style="width: 100%">
                    <div>
                      <van-tag type="danger">销量:{{ item.sales }}</van-tag>
                    </div>
                    <div>
                      <p class="font_x hui">
                        剩余库存:{{ item.inventory - item.sales }}
                      </p>
                    </div>
                  </div>
                  <!-- 3 -->
                  <div class="myflex" style="width: 100%">
                    <div>
                      <p
                        v-if="item.isPromote === 0"
                        class="red weight"
                        style="font-size: 14px"
                      >
                        ￥{{ item.price }}
                      </p>
                      <p
                        v-if="item.isPromote === 1"
                        class="red weight"
                        style="font-size: 14px"
                      >
                        ￥{{ item.promotePrice }}
                        <van-tag type="warning">促销</van-tag>
                      </p>
                    </div>
                    <div>
                      <div
                      style="display: flex;"
                        v-if="
                          item.carCount !== 0 && item.inventory - item.sales > 0
                        "
                      >
                        <div
                          class="iconfont icon-jian1 number"
                          @click="methods.minusGoodCar(item)"
                        ></div>
                        <div
                          class="discount-number plw prw "
                          style="font-size: 16px;padding-top: 2px;"
                        >
                          {{ item.carCount }}
                        </div>
                        <div
                          class="iconfont icon-jia number"
                          @click="methods.addGoodCar(item)"
                        ></div>
                      </div>

                      <div
                        v-if="
                          item.carCount === 0 && item.inventory - item.sales > 0
                        "
                      >
                        <div
                          class="iconfont icon-jia number"
                          @click="methods.addGoodCar(item)"
                        ></div>
                      </div>

                      <div v-if="item.inventory - item.sales <= 0">
                        <van-tag>已售罄</van-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div style="height: 5px; background: rgb(241, 241, 241)"></div>
          </div>

          <van-list
  v-model:loading="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="methods.onLoad"
>
</van-list>

        </div>


        <div v-if="shopData.length===0">
          <van-empty
  image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
  image-size="80"
  description="没有相关数据"
/>
        </div>


        </div>
      </van-pull-refresh>
     
      </van-skeleton>
      </div>
      <!-- 购物车 -->
      <div class="bottomcar">
        <div style="" class="carbox myflex">
          <div class="car myflex">
            <div
              class="iconfont icon-gouwuche"
              style="font-size: 22px; margin-left: 20px"
            >
              <van-badge
                :content="likeShop.count"
                style="position: relative; bottom: 18px"
              >
                <div class="child"></div>
              </van-badge>
            </div>
            <div style="margin-right: 1.5rem">
              合计:
              <span style="font-size: 18px; font-weight: bold"
                >￥{{ likeShop.price.toFixed(2) }}</span
              >
            </div>
          </div>
          <van-button class="car-btn" @click="router.push('/shop/home/buy')"> 去结算 </van-button>
        </div>
      </div>
      <!-- 购物车 -->
    </div>
 
  </div>
</template>

<script setup>
import { onMounted, ref,provide,watchEffect} from "vue";
import { searchGoods } from "@/api/good";
import { useRouter } from "vue-router";
import PackBack from '@/components/PageBack.vue'
const parentMessage = '搜索'; // 父组件数据
provide('mytitle', parentMessage); // 提供数据给子组件
const isSearch = ref(false); //是否已经点击搜索
const shopData = ref([]); //数据
const router=useRouter();
const isFirst=ref(true);
const myhistory=ref([]);    //搜索框历史
const list = ref([]);
    const loading = ref(false); //触底
    const finished = ref(false);  //数据到底
    const count = ref(0);  //下拉
    const loadingx = ref(false);  //下拉加载消失


const value = ref("");
const pages = ref({
  page: 1,
  limit: 10,
  total: 0,
  key: "",
});

const shopCar = ref([]); //当前页面购物车
const ids = ref([]); //购物车所有商品id
const likeShop = ref({
  price: 0,
  count: 0,
}); //购物车总数量和价格



const methods = {
  //下拉
  onRefresh : () => {
    pages.value.limit=10;
    pages.value.page=1;
    methods.merchantSearchGoods().then(()=>{
      loadingx.value=false;
    });
    },
    //触底
   onLoad : () => {
    pages.value.limit+=10;
    methods.merchantSearchGoods().then(()=>{
      loading.value=false;
    });



    },


  //点击历史记录执行
  historySearch:(item)=>{
    pages.value.key=item;
    value.value=item;
    isSearch.value = true;
    methods.merchantSearchGoods();
  },
    //去详情页面
    goDetail: (id) => {
    router.push("/shop/home/detail/" + id);
  },
  //更新页面数据
  updateData: (item) => {
    //所有缓存已有的商品的id
    const carIds = ids.value.map((d) => d.id);
    console.log(carIds, "在购物车的id", item);

    item.value.map((d, i) => {
      if (carIds.includes(d.id)) {
        console.log(1111111111111111111111111, d.id);
        const arr = ids.value.find((e) => e.id === d.id);
        d.carCount = arr.carCount;
      } else {
        d.carCount = 0;
      }
      //这个页面因为有子集所以需要改变成这个方案
      // d.goods.map((e)=>{
      //   if (carIds.includes(e.id)) {
      //   const arr = ids.value.find((f) => f.id === e.id);
      //   e.carCount = arr.carCount;
      // } else {
      //   e.carCount = 0;
      // }
      // })
    });
  },

  //更新购物车数据
  save: (shop) => {
    const result = shop.value.find((d) => d.carCount === 0);
    if (result) {
      shop.value.map((d, i) => {
        if (d.carCount === 0) {
          shop.value.splice(i, 1);
        }
      });
    }
    //存入最新数据
    localStorage.setItem("shopCar", JSON.stringify(shop.value));

    //更新数据
    shopCar.value = JSON.parse(localStorage.getItem("shopCar"));

    likeShop.value.price = 0;
    likeShop.value.count = 0;
    shopCar.value.map((d) => {
      if (d.isPromote === 1) {
        likeShop.value.price += d.promotePrice * d.carCount;
      }

      if (d.isPromote === 0) {
        likeShop.value.price += d.price * d.carCount;
      }
      likeShop.value.count += d.carCount;
    });
  },

  //购物车新增
  addGoodCar: (item) => {
    //查看购物车是否已经存在
    const result = shopCar.value.find((d) => d.id === item.id);
    if (result) {
      //已经存在，数量+1
      shopCar.value.map((d) => {
        if (item.id === d.id) {
          d.carCount += 1;

          //更新id库中的数据
          ids.value.map((e) => {
            if (e.id === d.id) {
              e.carCount += 1;
            }
          });
        }
      });
    }

    if (!result) {
      //不存在，添加进购物车
      shopCar.value.push({ ...item, carCount: 1 });
      ids.value.push({ id: item.id, carCount: 1 });
    }

    //更新存储数据
    methods.save(shopCar);
    //更新页面数据
    methods.updateData(shopData);
  },

  //购物车减少
  minusGoodCar: (item) => {
    //查看购物车是否已经存在
    const result = shopCar.value.find((d) => d.id === item.id);
    if (result.carCount >= 1) {
      //已经存在，数量-1
      shopCar.value.map((d) => {
        if (item.id === d.id) {
          d.carCount -= 1;

          //更新id库中的数据
          ids.value.map((e, i) => {
            if (e.id === d.id) {
              e.carCount -= 1;
            }
          });
        }
      });
    }

    //数量为0，在购物车中清除 在ids库中清除
    if (result.carCount === 0) {
      console.log("清除ids");
      shopCar.value.map((d, i) => {
        if (item.id === d.id) {
          shopCar.value.splice(i, 1);
        }
      });
      ids.value.map((d, i) => {
        if (item.id === d.id) {
          ids.value.splice(i, 1);
        }
      });
    }

    //更新存储数据
    methods.save(shopCar);
    //更新页面数据
    methods.updateData(shopData);
  },
  //历史分割
  updateHistory:(d)=>{
      if(d.value.length>=6){
        d.value= d.value.splice(0,4);
      }

      localStorage.setItem("searchShopM",JSON.stringify(d.value));
      myhistory.value=JSON.parse(localStorage.getItem("searchShopM"));
  },

  /**
   * 搜索按钮事件
   */
  onSearch: (value) => {
    pages.value.limit=10;
    if(value!=""){
      myhistory.value.unshift(value);
    }
    methods.updateHistory(myhistory)
    pages.value.key = value;
    isSearch.value = true;
    methods.merchantSearchGoods();
  },
  /**
   * 模糊查询
   */
  merchantSearchGoods: async () => {
    const res = await searchGoods({
      page: pages.value.page,
      limit: pages.value.limit,
      key: pages.value.key,
    });

    if (res.result === 0) {
     if(isSearch.value===true && isFirst.value===true){
        isFirst.value=false;
     }
      shopData.value = res.data.data;
      methods.updateData(shopData);
      pages.value.total=res.data.total;
      if(pages.value.limit>=pages.value.total){
        finished.value = true;
      }else{
        finished.value = false;
      }
      console.log(pages.value.total);
    }
  },
};

onMounted(() => {
  //  特别注意:页面初始数据要在购买数量的处理在获取页面的方法中处理

  const shopCar_history = localStorage.getItem("shopCar");
  const searchShopM = localStorage.getItem("searchShopM");
  //符合条件即为不需要初始化购物车
  if (shopCar_history !== "" && shopCar_history !== null) {
    //不需要初始化购物车，将历史购物车赋值当前页面
    //缓存中的购物车
    const cars = JSON.parse(shopCar_history);
    cars.map((d) => {
      // 购买数量和价格处理
      if (d.isPromote === 1) {
        likeShop.value.price += d.promotePrice * d.carCount;
      }

      if (d.isPromote === 0) {
        likeShop.value.price += d.price * d.carCount;
      }
      likeShop.value.count += d.carCount;
    });

    //赋值给本地的购物车
    shopCar.value = cars;
    //赋值给本地的购物车id和数量
    ids.value = cars.map((d) => ({ id: d.id, carCount: d.carCount }));
  } else {
    //初始化购物车
    localStorage.setItem("shopCar", JSON.stringify([]));
  }

  
  if(searchShopM !== "" && searchShopM !== null){
    const historys = JSON.parse(searchShopM);
    myhistory.value = historys;
  }else {
    //初始化搜索历史
    localStorage.setItem("searchShopM", JSON.stringify([]));
  }

  methods.merchantSearchGoods();
});





</script>

<style  scoped>
.number {
  color: red;
  font-size: 22px;
}

/* 购物车start */
/* 右侧去结算按钮 */
.car-btn {
  flex: 2;
  height: 100%;
  background: #f04516;
  color: #fff;
  font-weight: bold;
  font-size: 18px;
  border: none;
  border-radius: 0px 50px 50px 0px;
}

/* 购物车整个盒子 */
.carbox {
  height: 40px;
  margin: auto;
  position: relative;
  margin-bottom: 10px;
  width: 96%;
}
.bottomcar {
  position: fixed;
  width: 100%;
  bottom: 0px;
  /* background: #fff; */
}
/* 购物车左侧 */
.car {
  flex: 8;
  height: 100%;
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 12px;
  border-radius: 50px 0px 0px 50px;
  background: linear-gradient(to right, #e97f08, #ea8012);
}
/* .discount-number{
  font-size: 14px !important;
} */
/* 购物车end */

.historys div {
  margin-top: 10px;
  margin-left: 10px;
  /* float: left; */
  padding: 0px 8px 0px 8px;
  text-align: center;
  background: #efefef;
  border-radius: 14px;
  height: 30px;
  min-width: 30px;
  line-height: 30px;
  color: #fd9c74;
  font-weight: 500;
  font-size: 14px;
}

.historys {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebedf0;
}

p {
  margin: 3px;
}
</style>